const fs = require('fs')//引入文件模块
const path = require('path') //引入路径模块

const source = path.resolve(__dirname,'./MyFiles/source.txt')
const target = path.resolve(__dirname,'./MyFiles/target.txt')

//创建可读流和可写流对象
const rs = fs.createReadStream(source,{
    highWaterMark: 3
})
const ws = fs.createWriteStream(target,{
    highWaterMark: 2,
})

//监听data事件
rs.on('data',(chunk)=>{
    //读取到数据chunk并写入
    const flag = ws.write(chunk)
    if(flag){
        //说明写入缓冲区已经满了,如果在继续写入的话就要占用内存了
        //这里使用fs.pause先将读取操作暂停
        rs.pause()
    }
})

ws.on('drain',()=>{
    console.log('可写缓存区已经被清空了,可以继续写入文件内容')
    rs.resume()
})